<?php

namespace app\hook;

use app\service\config;
use app\traits\stocksale;

class ordercreate
{
    use stocksale;

    public function before($params = [])
    {
        // 处理秒杀库存

        \Log::out('hook:order_create_before emitted. params:' . json_encode($params), 'hook');
    }

    public function after($params = [])
    {
        $order = \orderModel::query()->find($params['orderId']);

        // 删除购物车
        if ($params['from'] == 'cart') {
            \cartModel::where('member_id', $order->member_id)->delete();
        }

        // 积分订单冻结支付积分数额
        if ($order->type == 'score' && $order->score_fee > 0) {
            \memberModel::freezeScore($order->score_fee, $order->member_id, $order->id);
        }

        // 订单减库存
        $this->realForwardStockSale($order);

        $order_ext = json_decode($order->getRawOriginal('ext'), true);
        $order_ext['buy_type'] = $params['buy_type'] ?? 'alone';  // 购买方式，alone： 单独购买， groupon: 拼团
        $order_ext['groupon_id'] = $groupon['id'] ?? 0;   // 如果是拼团，团 id

        // 计算订单过期时间等附加信息
        $config = config::get('order');
        $minutes = (int) ($config['order_auto_close'] ?? 30);
        $order_ext['expired_time'] = time() + ($minutes * 60);
        $order_ext['pay_wait_minutes'] = $minutes;

        // 更新订单扩展字段
        $order->ext = json_encode($order_ext);
        $order->save();

        \Queue::later(($minutes * 60), 'app\job\OrderAutoOper@autoClose', ['order' => $order], 'shop');
    }
}

